package com.yanfan.njLighting.quartz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.yanfan.common.utils.DateUtils;
import com.yanfan.njLighting.domain.NjLightingDevice;
import com.yanfan.njLighting.domain.NjLightingDeviceStatus;
import com.yanfan.njLighting.service.INjLightingDeviceService;
import com.yanfan.njLighting.service.INjLightingDeviceStatusService;
import com.yanfan.njLighting.utils.Modbus4jUtils;
import com.yanfan.njLighting.utils.ModbusOffsetUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component("njLightingTask")
public class GetModbusTcpLightingDataJob {

    @Resource
    private INjLightingDeviceService lightingDeviceService;
    @Resource
    private INjLightingDeviceStatusService lightingDeviceStatusService;

    /**
     * 定时智能照明回路状态
     *
     * @throws ModbusTransportException
     * @throws ErrorResponseException
     * @throws ModbusInitException
     */
    public void getLightingStatus() throws ModbusInitException {
        // 处理单独读取结果的列表
        List<NjLightingDevice> deviceList = lightingDeviceService.list(new LambdaQueryWrapper<NjLightingDevice>()
                .orderByAsc(NjLightingDevice::getDeviceOffset));

        ArrayList<NjLightingDeviceStatus> list = new ArrayList<>();
        deviceList.stream().forEach(device -> {
            ModbusMaster master = null;
            try {
                master = Modbus4jUtils.getMaster(device.getAddressIp(), 502);
            } catch (ModbusInitException e) {
                throw new RuntimeException(e);
            }
            // 定义一个从站 ID 和偏移量的列表
            int dataType = DataType.FOUR_BYTE_INT_UNSIGNED; // 数据类型
            // 获取寄存器偏移量
            String time = DateUtils.getTime();
            NjLightingDeviceStatus status = new NjLightingDeviceStatus();
            try {
                // 单独读取每个寄存器的数据
                Number number = Modbus4jUtils.readHoldingRegister(master,
                        1, Integer.valueOf(device.getDeviceOffset()), DataType.TWO_BYTE_INT_UNSIGNED);
                status.setDeviceCode(device.getDeviceCode());
                status.setDeviceType(device.getDeviceType());
                status.setAddressIp(device.getAddressIp());
                status.setDeviceName(device.getDeviceName());
                status.setPosition(device.getPosition());
                status.setDeviceOffset(device.getDeviceOffset());
                status.setStatus((Integer) number);
                status.setUpdateTime(time);
            } catch (Exception e) {
                // 单个寄存器读取失败，设置默认值并记录错误
                System.out.println("读取设备 " + " 时发生异常：" + e.getMessage());
            }
            list.add(status);

        });
        lightingDeviceStatusService.saveOrUpdateBatch(list);

    }
}
